package dp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LargestDivisibleSubset368 {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int[] dp = new int[nums.length];
        Arrays.sort(nums);
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
        }

        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = Math.max(dp[j] + 1, dp[i]);
                }
            }
        }
        int max = 0;
        for (int i = 0; i < dp.length; i++) {
            max = Math.max(dp[i], max);
        }

        List<Integer> result = new ArrayList<>();
        for (int i = dp.length - 1; i >= 0; i--) {
            if (dp[i] == max) {
                if (result.size() > 0) {
                    if (result.get(result.size() - 1) % nums[i] == 0) {
                        max--;
                        result.add(nums[i]);
                    }
                } else {
                    max--;
                    result.add(nums[i]);
                }
            }
        }


        return result;
    }
}
